package com.synjones.zeuscloudweb.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.synjones.zeus.model.web.AdminBean;
import com.synjones.zeus.model.web.AdminRoleBean;
import com.synjones.zeus.model.web.RoleBean;
import com.synjones.zeuscloudweb.config.MyConfig;
import com.synjones.zeuscloudweb.service.AdminService;
import com.synjones.zeuscloudweb.service.RoleService;
import com.synjones.zeuscloudweb.util.ccl.datastructure.impl.BaseDto;
import com.synjones.zeuscloudweb.util.ccl.util.G4Utils;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author yys
 * Description: 用户管理
 * @date created in 15:25 2017/12/29
 * Modified by:
 */
@Controller
@RequestMapping("admin")
public class AdminController  {
    private final Logger logger = LoggerFactory.getLogger(AdminController.class);
    @Autowired
    @Qualifier("adminServiceImpl")
    private AdminService adminService;
    @Autowired
    @Qualifier("roleServiceImpl")
    private RoleService roleService;
    @Resource
    private MyConfig myConfig;

    /**
     * 用户管理页面跳转
     *
     * @param
     * @return throws
     * @author yys
     * description
     * @date 15:36 2017/12/29
     */
    @RequestMapping(value = "/adminListInfo", method = RequestMethod.GET)
    public String adminListInfo() {
        return "admin-list";
    }

    /**
     * 添加用户页面跳转
     *
     * @param
     * @author yys
     * description:  添加用户页面跳转
     * @date 15:02 2018-01-08
     * return:
     */
    @RequestMapping(value = "/addAdminInfo", method = RequestMethod.GET)
    public String addAdminInfo(Model model) {
        List<RoleBean> roleList = roleService.selectRole();
        model.addAttribute("roleList", roleList);
        return "admin-add";
    }

    /**
     * 修改用户页面跳转
     *
     * @param
     * @return throws
     * @author yys
     * Description:  修改用户页面跳转
     * @date 15:41 2018-01-10
     */
    @RequestMapping(value = "/updateAdminInfo", method = RequestMethod.GET)
    public String updateAdminInfo(Model model, @Param("userId") String userId) {
        AdminBean adminBean = adminService.selectAdminByUserId(userId);
        List<RoleBean> roleList = roleService.selectRole();
        AdminRoleBean adminRoleVO = roleService.selectAdminRoleByUserId(userId);
        model.addAttribute("roleList", roleList);
        model.addAttribute("adminVO", adminBean);
        model.addAttribute("adminRoleVO", adminRoleVO);
        return "admin-update";
    }

    /**
     * 管理员个人信息页面跳转
     *
     * @param userId 管理员 userId
     * @return throws
     * @author yys
     * Description:  管理员个人信息页面跳转
     * @date 15:41 2018-01-10
     */
    @RequestMapping(value = "/selectAdminInfo", method = RequestMethod.GET)
    public String selectAdminInfo(Model model, @Param("userId") String userId) {
        AdminBean adminBean = adminService.selectAdminByUserId(userId);
        List<RoleBean> roleList = roleService.selectRole();
        AdminRoleBean adminRoleVO = roleService.selectAdminRoleByUserId(userId);
        model.addAttribute("roleList", roleList);
        model.addAttribute("adminVO", adminBean);
        model.addAttribute("adminRoleVO", adminRoleVO);
        return "admin-select";
    }

    /**
     * 管理员添加
     *
     * @param adminBean
     * @author yys
     * description
     * @date 16:49 2018-01-08
     * return:
     */
    @RequestMapping(value = "/addAdmin", method = RequestMethod.POST)
    public void addAdmin(AdminBean adminBean, @Param("roleId") String roleId, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDto;
        int count = 0;
        try {
            if (G4Utils.isNotEmpty(adminBean) && G4Utils.isNotEmpty(adminBean.getUserName())) {
                count = adminService.selectCountAdminByAdminName(adminBean.getUserName());
            }
            if (count > 0) {
                jsonDto = new BaseDto();
                jsonDto.put("success", new Boolean(false));
                jsonDto.put("msg", "此用户名已被注册,请重新输入!");
                pw.write(JSONObject.fromObject(jsonDto).toString());
            } else {
                String password = G4Utils.encryptBasedDes(adminBean.getPassword());
                adminBean.setPassword(password);
                jsonDto = adminService.insertAdmin(adminBean, roleId);
                Boolean boole = (Boolean) jsonDto.get("success");
                if (boole) {
                    logger.debug(G4Utils.getCurrentTime() + "账户" + adminBean.getUserName() + "注册到系统中!");
                } else {
                    logger.debug(G4Utils.getCurrentTime() + "账户" + adminBean.getUserName() + "注册失败!");
                }
                pw.write(JSONObject.fromObject(jsonDto).toString());
            }
        } catch (Exception e) {
            jsonDto = new BaseDto();
            jsonDto.put("success", new Boolean(true));
            jsonDto.put("msg", "添加失败!");
            pw.write(JSONObject.fromObject(jsonDto).toString());
        } finally {
            pw.close();
        }
    }

    /**
     * 分页获取管理员
     *
     * @author yys
     * description
     * @date 11:37 2018-01-10
     * return:
     */
    @RequestMapping(value = "/selectAdminByPage", method = RequestMethod.POST)
    public void selectAdminByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        //直接返回前台
        String draw = request.getParameter("draw");
        //数据起始位置
        String startIndex = request.getParameter("startIndex");
        //每页显示的条数
        String pageSize = request.getParameter("pageSize");
        //获取排序字段
        String orderColumn = request.getParameter("orderColumn");
        //开始时间
        String startTime = request.getParameter("startTime");
        //结束时间
        String endTime = request.getParameter("endTime");
        //获取查询字段
        String userName = request.getParameter("userName");
        if (orderColumn == null) {
            orderColumn = "USERID";
        }
        //获取排序方式
        String orderDir = request.getParameter("orderDir");
        if (orderDir == null) {
            orderDir = "asc";
        }
        AdminBean adminBean = new AdminBean();
        if (null != userName && !"".equals(userName)) {
            adminBean.setUserName(userName);
        }
        //分页处理，显示第一页的10条数据
        Page<AdminBean> page = PageHelper.offsetPage((Integer.parseInt(startIndex)), (Integer.parseInt(pageSize)));
        adminService.selectAdminByPage(startTime, endTime, orderColumn, orderDir, adminBean);
        PageInfo<AdminBean> pageInfo = new PageInfo<>(page);
        Map<Object, Object> info = new HashMap<Object, Object>();
        info.put("pageData", pageInfo.getList());
        info.put("total", pageInfo.getTotal());
        info.put("draw", draw);
        pw.write(JSONObject.fromObject(info).toString());
        pw.close();
    }

    /**
     * 修改用户启用/停用状态
     *
     * @param adminBean
     * @return throws
     * @author yys
     * description
     * @date 11:42 2018-01-10
     */
    @RequestMapping(value = "/updateAdminAvailable", method = RequestMethod.POST)
    public void updateAdminAvailable(HttpServletResponse response, AdminBean adminBean) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDto = new BaseDto();
        if (G4Utils.isNotEmpty(adminBean.getUserId()) && G4Utils.isNotEmpty(adminBean.getAvailable())) {
            try {
                adminService.updateAdminAvailable(adminBean);
                logger.debug("ID为" + adminBean.getUserId() + "修改AVAILABLE=" + adminBean.getAvailable());
                jsonDto.put("userId", adminBean.getUserId());
                jsonDto.put("success", new Boolean(true));
                jsonDto.put("msg", "操作成功!");
                pw.write(JSONObject.fromObject(jsonDto).toString());
            } catch (Exception e) {
                jsonDto.put("userId", adminBean.getUserId());
                jsonDto.put("success", new Boolean(false));
                jsonDto.put("msg", "操作失败请联系管理员!");
                pw.write(JSONObject.fromObject(jsonDto).toString());
            } finally {
                pw.close();
            }
        } else {
            jsonDto.put("userId", adminBean.getUserId());
            jsonDto.put("success", new Boolean(false));
            jsonDto.put("msg", "操作失败请联系管理员!");
            pw.write(JSONObject.fromObject(jsonDto).toString());
            pw.close();
        }
    }

    /**
     * 修改用户信息
     *
     * @param adminBean
     * @return throws
     * @author yys
     * description
     * @date 9:38 2018-01-11
     */
    @RequestMapping(value = "/updateAdminByUserId", method = RequestMethod.POST)
    public void updateAdminByUserId(HttpServletResponse response, @Param("roleId") String roleId,
                                    AdminBean adminBean) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDto = new BaseDto();
        try {
            adminBean.setPassword(G4Utils.encryptBasedDes(adminBean.getPassword()));
            jsonDto = adminService.updateAdminByUserId(adminBean, roleId);
            Boolean boole = (Boolean) jsonDto.get("success");
            if (boole) {
                logger.debug(G4Utils.getCurrentTime() + "账户" + adminBean.getUserName() + "的信息被修改!");
            } else {
                logger.debug(G4Utils.getCurrentTime() + "账户" + adminBean.getUserName() + "的信息修改失败!");
            }
            pw.write(JSONObject.fromObject(jsonDto).toString());
        } catch (Exception e) {
            jsonDto.put("userId", adminBean.getUserId());
            jsonDto.put("success", new Boolean(false));
            jsonDto.put("msg", "操作失败请联系管理员!");
            pw.write(JSONObject.fromObject(jsonDto).toString());
        } finally {
            pw.close();
        }
    }

    /**
     * 根据id删除用户
     *
     * @param userId
     * @return throws
     * @author yys
     * description
     * @date 12:02 2018-01-11
     */
    @RequestMapping(value = "deleteAdminByUserId", method = RequestMethod.POST)
    public void deleteAdminByUserId(@RequestParam("userId") String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        String[] userIds = userId.split(",");
        BaseDto jsonDto = adminService.deleteAdminByUserId(userIds);
        pw.write(JSONObject.fromObject(jsonDto).toString());
        pw.close();

    }
}